package cn.slipi.provider.biz;

import cn.hutool.core.lang.UUID;
import cn.slipi.common.exception.BizException;
import cn.slipi.common.utils.JsonUtil;
import cn.slipi.facade.api.message.form.MessageForm;
import cn.slipi.provider.facade.MessageCallFacade;
import cn.slipi.service.entity.TOrder;
import cn.slipi.service.entity.TPay;
import cn.slipi.service.service.TOrderService;
import cn.slipi.service.service.TPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class PayBiz {

    @Value("${spring.application.name}")
    private String appName;

    @Value("${order.routing.key}")
    private String orderRoutingKey;

    @Autowired
    private TPayService payService;

    @Autowired
    private TOrderService orderService;

    @Autowired
    private MessageCallFacade messageCallFacade;

    @Transactional(rollbackFor = BizException.class)
    public String doPay(String orderNo) {
        //获取订单
        TOrder order = this.orderService.getOrderByNo(orderNo);
        //创建支付单
        String payNo = UUID.randomUUID().toString();
        TPay pay = new TPay();
        pay.setOrderNo(order.getOrderNo());
        pay.setPayNo(payNo);
        pay.setAmount(order.getAmount());
        pay.setState(0);
        int payId = this.payService.getBaseMapper().insert(pay);
        //写入消息
        MessageForm messageForm = new MessageForm();
        messageForm.setObjId(order.getOrderNo());
        messageForm.setAppName(this.appName);
        messageForm.setMessageContent(JsonUtil.object2Json(messageForm));
        messageForm.setRoutingKey(this.orderRoutingKey);
        this.messageCallFacade.prepareMessage(messageForm);
        //执行本地业务（修改支付单为支付成功）
        pay.setId(payId);
        pay.setState(1);
        this.payService.getBaseMapper().updateById(pay);
        //发送消息（通知修改订单状态为待发货）
        this.messageCallFacade.confirmMessage(order.getOrderNo());
        return order.getOrderNo();
    }
}
